package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.*;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.AttrService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Resource
    private AttrAttrgroupRelationDao attrAttrgroupRelationDao;
    @Resource
    private AttrGroupDao attrGroupDao;
    @Resource
    private CategoryDao categoryDao;
    @Resource
    private AttrGroupServiceImpl attrGroupServiceImpl;
    @Resource
    private ProductAttrValueDao productAttrValueDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public PageUtils selectDetail(Map<String, Object> params, Integer catelogId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<>();
        if(attrType.equalsIgnoreCase(ProductConstant.AttrType.ATTR_TYPE_SALE.getMessage())) {
            wrapper.eq("attr_type",ProductConstant.AttrType.ATTR_TYPE_SALE.getCode());
        }
        String key = (String) params.get("key");
        if(catelogId != 0) {
            wrapper.eq("catelog_id",catelogId);
        }
        if(!StringUtils.isEmpty(key)) {
            wrapper.and((obj) -> {
                obj.eq("attr_id",key).or().like("attr_name",key);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                wrapper
        );
        List<AttrEntity> records = page.getRecords();
        List<AttrRespVo> respVoList = records.stream().map((attrEntity) -> {
            AttrRespVo attrVo = new AttrRespVo();
            BeanUtils.copyProperties(attrEntity, attrVo);
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
            if(!StringUtils.isEmpty(attrAttrgroupRelationEntity)) {
                AttrGroupEntity entity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
                if (!StringUtils.isEmpty(entity)) {
                    attrVo.setGroupName(entity.getAttrGroupName());

                }
            }
            CategoryEntity attrGroup = categoryDao.selectOne(new QueryWrapper<CategoryEntity>().eq("cat_id",attrEntity.getCatelogId()));
            if (!StringUtils.isEmpty(attrGroup)) {
                attrVo.setCatelogName(attrGroup.getName());
            }
            return attrVo;
        }).collect(Collectors.toList());
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(respVoList);
        return pageUtils;
    }

    @Override
    public void updateDetail(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr,attrEntity);
        this.updateById(attrEntity);

        Long count = attrAttrgroupRelationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));

        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        if(attrEntity.getAttrId() != null) {
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
        }
        if(attr.getAttrGroupId() != null){
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
        }
        if(attrEntity.getAttrType() == ProductConstant.AttrType.ATTR_TYPE_BASE.getCode()) {

            if(count > 0 ) {
                attrAttrgroupRelationDao.update(attrAttrgroupRelationEntity,new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id",attrEntity.getAttrId()));
            }else{
                attrAttrgroupRelationDao.insert(attrAttrgroupRelationEntity);
            }
        }
    }

    @Override
    public AttrRespVo getDetail(Long attrId) {
        AttrEntity attrEntity = this.getById(attrId);
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity,attrRespVo);
        ArrayList<Long> paths = new ArrayList<>();
        attrGroupServiceImpl.findCateLogPath(attrEntity.getCatelogId(),paths);
        Collections.reverse(paths);
        attrRespVo.setCatelogPath((Long[]) paths.toArray(new Long[0]));
        AttrAttrgroupRelationEntity attrGroupEntity = attrAttrgroupRelationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if(!StringUtils.isEmpty(attrGroupEntity)){
           attrRespVo.setAttrGroupId(attrGroupEntity.getAttrGroupId());
            return attrRespVo;
        }
        return attrRespVo;
    }

    @Override
    public List<AttrEntity> getRelationInfo(Long attrgroupId) {

        List<AttrAttrgroupRelationEntity> relationEntityList = attrAttrgroupRelationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrgroupId));
        List<Long> attrIds = relationEntityList.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        List<AttrEntity> entities = baseMapper.selectList(new QueryWrapper<AttrEntity>().in("attr_id", attrIds));

        return entities;

    }

    @Override
    public PageUtils getNoattrRelation(Map<String, Object> params, Long attrgroupId) {
        String key = (String) params.get("key");
        AttrGroupEntity attrGroup = attrGroupDao.selectById(attrgroupId);
        QueryWrapper<AttrGroupEntity> wrapper1 = new QueryWrapper<AttrGroupEntity>().eq("catelog_id", attrGroup.getCatelogId());
        List<AttrGroupEntity> attrGroupEntities = attrGroupDao.selectList(wrapper1);
        List<Long> attrGroupIds = attrGroupEntities.stream().map(AttrGroupEntity::getAttrGroupId).collect(Collectors.toList());
        QueryWrapper<AttrAttrgroupRelationEntity> wrapper = new QueryWrapper<>();
        wrapper.in("attr_group_id",attrGroupIds);
        List<AttrAttrgroupRelationEntity> attrAttrgroupRelationEntity = attrAttrgroupRelationDao.selectList(wrapper);
        List<Long> attrIds = attrAttrgroupRelationEntity.stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("catelog_id",attrGroup.getCatelogId()).eq("attr_type",ProductConstant.AttrType.ATTR_TYPE_BASE.getCode());
        if(attrIds != null && attrIds.size() > 0) {
            queryWrapper.notIn("attr_id",attrIds);
        }
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and(obj -> {
                obj.like("attr_id",key).or().like("attr_name",key);
            });
        }
//        List<AttrEntity> attrEntities = baseMapper.selectList(queryWrapper);
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        PageUtils utils = new PageUtils(page);

        return utils;

    }

    @Override
    public List<ProductAttrValueEntity> selectBaseSpuInfoBySpuId(Long spuId) {
        List<ProductAttrValueEntity> productAttrValueEntities = productAttrValueDao.selectList(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        return productAttrValueEntities;
    }

    @Override
    public void updateSpuInfo(Long spuId, List<ProductAttrValueEntity> productAttrValueEntityList) {
        productAttrValueDao.delete(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id",spuId));

        productAttrValueEntityList.forEach(e -> {
            e.setSpuId(spuId);
            productAttrValueDao.insert(e);
        });
    }

}
